import React, {Component} from 'react'
import Dimensions from 'react-dimensions'
import {fetchData} from '../../../components/AjaxConsumer'
import InstockTranLocModalTable from './instockTranLocModalTable'
import OutstockTranLocModalTable from './outstockTranLocModalTable'
import {
    Form,
    Input,
    Tooltip,
    Icon,
    Cascader,
    Select,
    Row,
    Col,
    Checkbox,
    Button,
    message,
    Modal,
    Radio
} from 'antd';
const RadioGroup = Radio.Group;
const FormItem = Form.Item;
const Option = Select.Option;
const confirm = Modal.confirm;

const children = [];
let sapSendSspot='';

class AreaForm extends React.Component {
    state = {
        loading: false,
        edit:false,
        submitUrl:'',
        whCodeList:[],
        regionCodeList:[],
        sendSpotList:[],
        factoryList:[],
        value:[],
        // instorageStrategyList:[
        //     {selectValue:'1',SelectName:'一步'},
        //     {selectValue:'2',SelectName:'两步'},
        // ],
        // priorityList:[
        //     {selectValue:'1',SelectName:'1'},
        //     {selectValue:'2',SelectName:'2'},
        //     {selectValue:'3',SelectName:'3'},
        //     {selectValue:'4',SelectName:'4'},
        // ],

        onetwoList:[
            {selectValue:'1',SelectName:'是'},
            {selectValue:'0',SelectName:'否'},
            
        ],

        activeFlagList:[
            {selectValue:'1',SelectName:'是'},
            {selectValue:'2',SelectName:'否'}
        ],
        formData:{
            areaId:'',
            areaCode:'',
            areaDesc:'',
            whCode:'',
            regionCode:'',
            instockTranLoc:'',
            outstockTranLoc:'',
            pickTranLoc:'',
            exSignLocNo:'',
            frozenLocNo:'',
            useTray:'',
            trayMix:'',
            instorageStrategy:'',
            outstorageStrategy:'',
            locPickFlag:'',
            allocationRule:'',
            priority:'',
            activeFlag:'',
            sapSendSspot:'',
            factoryCode:'',
        }
    };

// handleChange= (e) => {

//   sapSendSspot = e;
//   console.log("----www",sapSendSspot)//sap库存地点修改值改变后重新赋值
//   this.setState({
//       value:sapSendSspot
//   })

// }

    handleSubmit = (e) => {
        e.preventDefault();
        this.props.form.validateFieldsAndScroll((err, fieldsValue) => {
                if (!err) {
                    this.setState({loading: true});
                    let values = {
                        ...fieldsValue,
                    };
                    console.log('表单提交数据-----------',values);
                    //发送ajax 控制请求数据规则，无值的设为空
                    for (let item in values) {
                        if (!values[item]) {
                            values[item] = ''
                        }
                    }
                    

        //   console.log(sapSendSspot)
        //   let tmp = "";
        //   let tmp1 = "";
        //   for(let j = 0;j<sapSendSspot.length;j++){
        //       if(j<=sapSendSspot.length-2) {
        //           tmp1 = sapSendSspot[j] + ",";
        //       } else{
        //           tmp1 = sapSendSspot[j];
        //       }
        //       tmp = tmp + tmp1
        //   }
                  
                    // values.sapSendSspot = tmp;
                    console.log(values);
                    const options = {
                        url: this.state.submitUrl,
                        type: 'post',
                        condition: values
                    };
                    
                    fetchData(
                        this, 
                        options, 
                        (res) => {
                            //成功回调函数
                            this.setState({
                                loading:false
                            });
                            if (res.code == '1') {
                                message.success('操作成功');
                                
                                this.handleCancel();
                                this.props.refreshHandle();
                            }else{
                                //message.error(res.msg);
                            }
                        
                        },
                        (res) =>{
                            this.setState({
                                loading:false
                            });
                        }
                        )
                }
            });
    }

    handleCancel = () => {
    console.log("handleCancel......");    
    // //取消修改后将库存地点置为空
    // this.setState({
    //     value:[]
    // })
    this.props.onCancel();//123
    this.props.form.resetFields(); //初始化表单
    //初始化ajax加载过来的selectList
    }

    initRegion = (whCode) =>{
        if (whCode != '' && whCode != undefined){
            const options= {
                url: '/base/region/r/'+whCode+'/region',
                type: 'post',
                condition:{}
            };
            fetchData(this, options, (res) => {
                let optionList = [];
                res.data.map((e,index)=>{
                    let tmp = {};
                    tmp.selectValue = e.regionCode;
                    tmp.SelectName = e.regionDesc;
                    optionList.push(tmp);
                });
                this.setState({ regionCodeList: optionList })
            });
        } else {
            this.setState({ regionCodeList: [] })
        }
    }

    // 修改属性后刷新-n次
    componentWillReceiveProps(nextProps){
        if(nextProps.init){
            if(this.state.whCodeList.length==0){
                this.queryWarehousesUnderFactory();
            }
        }
        if (nextProps.initform) {
            this.props.form.resetFields(); //初始化表单
            this.props.initformCancel();
        }
        if (nextProps.formData.warehouseCode != this.state.formData.warehouseCode) {
            this.initRegion(nextProps.formData.warehouseCode);
        }
        console.log('componentWillReceiveProps------',nextProps);
        let tmpFormData = nextProps.formData;
        let url = nextProps.submitUrl;
        if(url=='/base/data/area/c'){
            this.setState({
                edit:false
            });
        }
        if(url=='/base/data/area/u'){
            this.setState({
                edit:true
            });
        }
        this.setState({
            formData:tmpFormData,
            submitUrl:nextProps.submitUrl
        });
        // //拿到值进行显示
        // var sapSendSspot=nextProps.formData.sapSendSspot;
        // console.log("拿到字符串",sapSendSspot)
        // if(sapSendSspot!=null){
        // var strs= new Array(); //定义一数组 
        
        // strs=sapSendSspot.split(","); //字符分割 
        // for (var i=0;i<strs.length ;i++ ) 
        // {
        //     if(strs[i]==""){
        //         delete strs[i];
        //         strs.length--
        //     }
        // } 
        // this.setState({
        //     value:strs
        // })
        // }else{
        //     this.setState({
        //     value:[]
        // })
        // }
        // this.state.str=strs
        //  console.log("xxx",strs)
        //  console.log("ssss",this.state.str)
        //  var sapSend=this.state.str;     
      
    }
    // 组件参数实例化-仅一次
    componentWillMount() {
        // console.log('componentWillMount-----',this.props);
        this.setState({
            submitUrl: this.props.submitUrl,
            formData: this.props.formData
        });
    }
    //初始化页面刷新-仅一次
    componentDidMount(){
        this.queryWarehousesUnderFactory();
        if (this.state.formData.whCode) {
            this.initRegion(this.state.formData.whCode);
        }
       // this.queryFactory();
        // this.querySendSpotUnderFactory();

   // for (let i = 10; i < 36; i++) {
   // children.push(<Option key={i.toString(36) + i}>{i.toString(36) + i}</Option>);
  //  }
    //    console.log("+++++++++++++++++"+children);
    }

    // 查询工厂
    queryFactory=()=>{
        let factoryCode = 'all';
        let options= {
            url: '/base/data/mdsendspot/r/factory',
            type: 'post',
            condition:{}
        };
        fetchData(this, options, (listData)=>{
            let optionList = [];
            listData.data.map( (e,index) => {
                let tmp = {};
                tmp.selectValue = e.factoryCode;
                tmp.SelectName = e.factoryName;
                optionList.push(tmp);
            });
            if(this.props.submitUrl=='/base/data/area/u'){
                this.setState({
                    edit:true,
                    factoryList:optionList
                });
            } else {
                this.setState({
                    edit:false,
                    factoryList:optionList
                });
            }
        });
    }

    // 查询工厂下的工位
    querySendSpotUnderFactory = () =>{
            const options= {
                url: '/base/data/mdsendspot/r/'+2+'/sendspot',
                type: 'post',
                condition:{}
            };
            fetchData(this, options, (res) => {
                let optionList = [];
                res.data.map((e,index)=>{
                    let tmp = {};
                    tmp.selectValue = e.sendSpot;
                    tmp.SelectName = e.sendSpot;
                    optionList.push(tmp);

                    children.push(<Option key={e.sendSpot}>{e.sendSpot}</Option>);
                  //  children.push(e.sendSpot);
                });
                this.setState({ sendSpotList: optionList })
            });
     
        this.props.form.setFieldsValue({sapSendSspot:''})
        //alert(factoryCode);
        //queryWarehousesUnderFactory();
    }
     // 查询工厂下的仓库
    queryWarehousesUnderFactory=()=>{
        //let factoryCode = 'all';
        let factoryCode = this.state.formData.factoryCode;
        let options= {
            url: '/base/data/warehouse/r/'+factoryCode+'/warehouse',
            type: 'post',
            condition:{}
        };
        fetchData(this, options, (listData)=>{
            let optionList = [];
            listData.data.map( (e,index) => {
                let tmp = {};
                tmp.selectValue = e.warehouseCode;
                tmp.SelectName = e.warehouseName;
                optionList.push(tmp);
            });
            console.log('仓库列表------',optionList);
            if(this.props.submitUrl=='/base/data/area/u'){
                this.setState({
                    edit:true,
                    whCodeList:optionList
                });
            } else {
                this.setState({
                    edit:false,
                    whCodeList:optionList
                });
            }
        });
    }
    // 仓库选择change后加载区域下拉框
    whCodeSelectChange = (whCode) =>{
        if (whCode != '' && whCode != undefined){
            const options= {
                url: '/base/region/r/'+whCode+'/region',
                type: 'post',
                condition:{}
            };
            fetchData(this, options, (res) => {
                let optionList = [];
                res.data.map((e,index)=>{
                    let tmp = {};
                    tmp.selectValue = e.regionCode;
                    tmp.SelectName = e.regionDesc;
                    optionList.push(tmp);
                });
                this.setState({ regionCodeList: optionList })
            });
        } else {
            this.setState({ regionCodeList: [] })
        }
        this.props.form.setFieldsValue({regionCode:''})
    }

    instockTranLocSearchClick = () =>{
        this.refs.instockTranLocModalTable.showModal();
    }

    outstockTranLocSearchClick = () =>{
        this.refs.outstockTranLocModalTable.showModal();
    }

    allocationRuleSearchClick = () =>{
        message.warn('当前区域分配规则还未开发');
    }

    // 入库出库弹出模态框的统一回调函数
    getLocationCodeTableData = (resultData) =>{
        if(resultData.type=='instock'){

            this.props.form.setFieldsValue(
                {
                    instockTranLoc:resultData.value
                }
            );
        }
        if(resultData.type=='outstock'){

            this.props.form.setFieldsValue(
                {
                    outstockTranLoc:resultData.value
                }
            );
        }
    }


    render() {
        const {getFieldDecorator} = this.props.form;
        const formItemLayout = {
            labelCol: {
                xs: {span: 24},
                sm: {span: 6}
            },
            wrapperCol: {
                xs: {span: 24},
                sm: {span: 14}
            }
        };
         /*
            如果 有弹出模态框表格 需要校验hasFeedback图标
            则需要使用此布局
        */
        const formItemLayout2 = {
            labelCol: {
                xs: {span: 24},
                sm: {span: 7}
            },
            wrapperCol: {
                xs: {span: 24},
                sm: {span: 16}
            }
        };
        const tailFormItemLayout = {
            wrapperCol: {
                xs: {span: 24,offset: 0},
                sm: {span: 24,offset: 10}
            }
        };
        //console.log("state.str的值",this.state.str)
        //一行几个 （总宽度24,）
        const colNumber = 12;//一行2个
           return (
            <div>
                <Form
                    onSubmit={this.handleSubmit}
                    style={{
                    backgroundColor: '#fff',
                    paddingTop: '20px',
                    paddingBottom: '20px'
                }}>
                    <Row>
                        <Col span={0}>
                                <FormItem>
                                    {getFieldDecorator('areaId',{
                                        initialValue: this.state.formData.areaId,
                                        rules: [
                                            {}
                                        ]
                                    })(<Input type="hidden"/>)}
                                </FormItem>
                        </Col>
                        <Col span={colNumber}>
                            <FormItem {...formItemLayout} label="库区编码" hasFeedback>
                                {getFieldDecorator('areaCode', {
                                    initialValue:this.state.formData.areaCode,
                                    rules: [
                                        {
                                            required: true,  message: '请输入库区编码'
                                        },{
                                            max:40,message: '输入内容应少于40个字符'
                                        },{
                                            pattern:/^[-a-zA-z0-9]*$/,message:'输入内容不合法'
                                        }
                                    ]
                                })(<Input disabled={this.state.edit}/>)}
                            </FormItem>
                        </Col>
                        <Col span={colNumber}>
                            <FormItem {...formItemLayout} label="库区描述" hasFeedback>
                                {getFieldDecorator('areaDesc', {
                                    initialValue:this.state.formData.areaDesc,
                                    rules: [
                                        {
                                            required: true, whitespace:true, message: '请输入库区描述'
                                        },{
                                            max:512,message: '输入内容应少于512个字符！'
                                        }
                                    ]
                                })(<Input />)}
                            </FormItem>
                        </Col>
                    </Row>
                        {/*<Col span={colNumber}>
                            <FormItem
                                {...formItemLayout}
                                label="工厂号"
                            >
                                <Row gutter={8}>
                                    {getFieldDecorator('factoryCode', {
                                        initialValue:this.state.formData.factoryCode,
                                        rules: [{
                                            message: '请选择工厂!'
                                        }],
                                    })(
                                        <Select
                                            placeholder="请选择"
                                            showSearch
                                            allowClear
                                            onChange={this.querySendSpotUnderFactory}
                                        >
                                            {
                                                this.state.factoryList.map((es,sIndex)=>{
                                                    return (
                                                        <Option key={sIndex} value={es.selectValue}>{es.SelectName}</Option>
                                                    )
                                                })
                                            }
                                        </Select>
                                    )}
                                </Row>
                            </FormItem>
                        </Col>*/}
                        {/* <Col span={colNumber}>
                            <FormItem
                                {...formItemLayout}
                                label="sap库存地点"
                            >
                                <Row gutter={8}>
                                  
                                        <Select
                                        mode="multiple"
                                            // disabled={this.state.edit}
                                            placeholder="请选择"
                                            showSearch
                                            allowClear
                                        id="sapSendSspot"
                                      // defaultValue={[]}
                                       value={this.state.value}  
                                        onChange={this.handleChange}
                                        >
                                            {
                                                children
                                            }
                                        </Select>
                                    
                                </Row>
                            </FormItem>
                        </Col> */}
                        <Row>
                        <Col span={colNumber}>
                            <FormItem
                                {...formItemLayout}
                                label="仓库编码"
                            >
                                <Row gutter={8}>
                                    {getFieldDecorator('whCode', {
                                        initialValue:this.state.formData.whCode,
                                        rules: [{
                                                 required: true, message: '请选择仓库编码!'
                                            }],
                                    })(
                                        <Select 
                                            disabled={this.state.edit}
                                            placeholder="请选择" 
                                            showSearch 
                                            allowClear
                                            onChange={this.whCodeSelectChange}
                                        >
                                            {
                                                this.state.whCodeList.map((es,sIndex)=>{
                                                    return (
                                                        <Option key={sIndex} value={es.selectValue}>{es.SelectName}</Option>
                                                    )
                                                })
                                            }
                                        </Select>
                                    )}
                                </Row>
                            </FormItem>
                        </Col>
                        <Col span={colNumber}>
                            <FormItem
                                {...formItemLayout}
                                label="区域编码"
                            >
                                <Row gutter={8}>
                                    {getFieldDecorator('regionCode', {
                                        initialValue:this.state.formData.regionCode,
                                        rules: [{
                                                 required: true, message: '请选择区域编码!'
                                            }],
                                    })(
                                        <Select 
                                            disabled={this.state.edit}
                                            placeholder="请选择" 
                                            showSearch 
                                            allowClear
                                        >
                                            {
                                                this.state.regionCodeList.map((es,sIndex)=>{
                                                    return (
                                                        <Option key={sIndex} value={es.selectValue}>{es.SelectName}</Option>
                                                    )
                                                })
                                            }
                                        </Select>
                                    )}
                                </Row>
                            </FormItem>
                        </Col>
                        </Row>
                        {/* <Row>
                        <Col span={colNumber}>
                            <Row gutter={0}>
                                <Col span={21}>
                                <FormItem
                                    {...formItemLayout2}
                                        label="入库过渡库位"
                                        hasFeedback
                                    >
                                    {getFieldDecorator('instockTranLoc', {
                                        initialValue:this.state.formData.instockTranLoc,
                                        rules: [
                                                {}
                                            ]
                                    })(
                                        <Input disabled/>
                                    )}
                                    </FormItem>
                                </Col>
                                <Col span={3} style={{paddingTop:'6px',boxSizing:'border-box'}}>
                                    <Icon type="search" style={{cursor:'pointer'}} onClick={this.instockTranLocSearchClick} />
                                </Col>
                            </Row>
                        </Col>
                        <Col span={colNumber}>
                            <Row gutter={0}>
                                <Col span={21}>
                                <FormItem
                                    {...formItemLayout2}
                                        label="出库过渡库位"
                                        hasFeedback
                                    >
                                    {getFieldDecorator('outstockTranLoc', {
                                        initialValue:this.state.formData.outstockTranLoc,
                                        rules: [
                                                {}
                                            ]
                                    })(
                                        <Input disabled/>
                                    )}
                                    </FormItem>
                                </Col>
                                <Col span={3} style={{paddingTop:'6px',boxSizing:'border-box'}}>
                                    <Icon type="search" style={{cursor:'pointer'}} onClick={this.outstockTranLocSearchClick} />
                                </Col>
                            </Row>
                        </Col>
                        </Row>
                        <Row>
                        <Col span={colNumber}>
                            <FormItem
                                {...formItemLayout}
                                label="入库策略"
                            >
                                <Row gutter={8}>
                                    {getFieldDecorator('instorageStrategy', {
                                        initialValue:this.state.formData.instorageStrategy,
                                        rules: [{
                                                 //required: true, message: '请选择区域!'
                                            }],
                                    })(
                                        <Select 
                                            placeholder="请选择" 
                                            showSearch 
                                            allowClear
                                        >
                                            {
                                                this.state.instorageStrategyList.map((es,sIndex)=>{
                                                    return (
                                                        <Option key={sIndex} value={es.selectValue}>{es.SelectName}</Option>
                                                    )
                                                })
                                            }
                                        </Select>
                                    )}
                                </Row>
                            </FormItem>
                        </Col>


                        <Col span={colNumber}>
                            <FormItem
                                {...formItemLayout}
                                label="出库策略"
                            >
                                <Row gutter={8}>
                                    {getFieldDecorator('outstorageStrategy', {
                                        initialValue:this.state.formData.outstorageStrategy,
                                        rules: [{
                                            //required: true, message: '请选择区域!'
                                        }],
                                    })(
                                        <Select
                                            placeholder="请选择"
                                            showSearch
                                            allowClear
                                        >
                                            {
                                                this.state.instorageStrategyList.map((es,sIndex)=>{
                                                    return (
                                                        <Option key={sIndex} value={es.selectValue}>{es.SelectName}</Option>
                                                    )
                                                })
                                            }
                                        </Select>
                                    )}
                                </Row>
                            </FormItem>
                        </Col>
                        </Row>
                        <Row>
                        <Col span={colNumber}>
                            <FormItem
                                {...formItemLayout}
                                label="是否使用托盘"
                            >
                                <Row gutter={8}>
                                    {getFieldDecorator('useTray', {
                                        initialValue:this.state.formData.useTray,
                                        rules: [{
                                            //required: true, message: '请选择区域!'
                                        }],
                                    })(
                                        <Select
                                            placeholder="请选择"
                                            showSearch
                                            allowClear
                                        >
                                            {
                                                this.state.onetwoList.map((es,sIndex)=>{
                                                    return (
                                                        <Option key={sIndex} value={es.selectValue}>{es.SelectName}</Option>
                                                    )
                                                })
                                            }
                                        </Select>
                                    )}
                                </Row>
                            </FormItem>
                        </Col>


                        <Col span={colNumber}>
                            <FormItem
                                {...formItemLayout}
                                label="是否托盘混载"
                            >
                                <Row gutter={8}>
                                    {getFieldDecorator('trayMix', {
                                        initialValue:this.state.formData.trayMix,
                                        rules: [{
                                            //required: true, message: '请选择区域!'
                                        }],
                                    })(
                                        <Select
                                            placeholder="请选择"
                                            showSearch
                                            allowClear
                                        >
                                            {
                                                this.state.onetwoList.map((es,sIndex)=>{
                                                    return (
                                                        <Option key={sIndex} value={es.selectValue}>{es.SelectName}</Option>
                                                    )
                                                })
                                            }
                                        </Select>
                                    )}
                                </Row>
                            </FormItem>
                        </Col>
                        </Row>
                        <Row>
                        <Col span={colNumber}>
                            <FormItem
                                {...formItemLayout}
                                label="是否库位拣货"//是否库位允许拣货
                            >
                                <Row gutter={8}>
                                    {getFieldDecorator('locPickFlag', {
                                        initialValue:this.state.formData.locPickFlag,
                                        rules: [{
                                            //required: true, message: '请选择区域!'
                                        }],
                                    })(
                                        <Select
                                            placeholder="请选择"
                                            showSearch
                                            allowClear
                                        >
                                            {
                                                this.state.onetwoList.map((es,sIndex)=>{
                                                    return (
                                                        <Option key={sIndex} value={es.selectValue}>{es.SelectName}</Option>
                                                    )
                                                })
                                            }
                                        </Select>
                                    )}
                                </Row>
                            </FormItem>
                        </Col>


                        <Col span={colNumber}>
                            <Row gutter={0}>
                                <Col span={21}>
                                <FormItem
                                    {...formItemLayout2}
                                        label="默认分配规则"
                                        hasFeedback
                                    >
                                    {getFieldDecorator('allocationRule', {
                                        initialValue:this.state.formData.allocationRule,
                                        rules: [
                                                {}
                                            ]
                                    })(
                                        <Input disabled/>
                                    )}
                                    </FormItem>
                                </Col>
                                <Col span={3} style={{paddingTop:'6px',boxSizing:'border-box'}}>
                                    <Icon type="search" style={{cursor:'pointer'}} onClick={this.allocationRuleSearchClick} />
                                </Col>
                            </Row>
                        </Col>
                        </Row>
                        <Row>
                        <Col span={colNumber}>
                            <FormItem
                                {...formItemLayout}
                                label="优先级"
                            >
                                <Row gutter={8}>
                                    {getFieldDecorator('priority', {
                                        initialValue:this.state.formData.priority,
                                        rules: [{
                                                 //required: true, message: '请选择仓库!'
                                            }],
                                    })(
                                        <Select 
                                            placeholder="请选择" 
                                            showSearch 
                                            allowClear
                                        >
                                            {
                                                this.state.priorityList.map((es,sIndex)=>{
                                                    return (
                                                        <Option key={sIndex} value={es.selectValue}>{es.SelectName}</Option>
                                                    )
                                                })
                                            }
                                        </Select>
                                    )}
                                </Row>
                            </FormItem>
                        </Col> */}
                        <Row>
                        <Col span={colNumber}>
                            <FormItem
                                {...formItemLayout}
                                label="激活标记"
                            >
                                <Row gutter={8}>
                                    {getFieldDecorator('activeFlag', {
                                        initialValue:this.state.formData.activeFlag,
                                        rules: [{
                                                    required: true, message: '请选择激活标记!'
                                            }]
                                    })(
                                        <Select placeholder="请选择" showSearch allowClear >
                                            {
                                                    this.state.activeFlagList.map((es,sIndex)=>{
                                                    return (
                                                        <Option key={sIndex} value={es.selectValue}>{es.SelectName}</Option>
                                                    )
                                                })
                                            }
                                        </Select>
                                    )}
                                </Row>
                            </FormItem>
                        </Col>
                        <Col span={24}>
                            <FormItem {...tailFormItemLayout}>
                                <Button type="primary" htmlType="submit" size="large">{this.state.loading?'提交中...':'确定'}</Button>
                                <Button
                                    type="default"
                                    style={{marginLeft: '50px'}}
                                    size="large"
                                    onClick={this.handleCancel}
                                >
                                    取消
                                </Button>
                            </FormItem>
                        </Col>

                    </Row>
                </Form>
                
                {/* <InstockTranLocModalTable getTableData={this.getLocationCodeTableData} ref='instockTranLocModalTable' />
                <OutstockTranLocModalTable getTableData={this.getLocationCodeTableData} ref='outstockTranLocModalTable' /> */}
            </div>
        );
    }
}

export default Form.create()(AreaForm);
